package com.fanshuai.jmx.jvm;

import java.lang.management.*;
import java.util.List;

public class MemoryReporter {
    public static void report() {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

        //gc
        memoryMXBean.gc();

        //memory usage
        MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
        System.out.println(memoryUsage.getUsed());

        /**
         * 垃圾回收器：
         PS收集器：
         PS Scavenge
         PS MarkSweep

         G1收集器：
         G1 Old Generation
         G1 Young Generation
         */
        List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean mxBean : garbageCollectorMXBeans) {
            System.out.println(mxBean.getCollectionTime());
        }

        /**
         * 内存管理器
         * CodeCacheManager
         * Metaspace Manager
         */
        List<MemoryManagerMXBean> memoryManagerMXBeans = ManagementFactory.getMemoryManagerMXBeans();
        for (MemoryManagerMXBean mxBean : memoryManagerMXBeans) {
            System.out.println(mxBean.getName());
        }

        /**
         * 内存池  java程序有多个内存池
         * 堆内存：
         *
         * PS收集器：
         * PS Eden Space
           PS Survivor Space
           PS Old Gen

           G1收集器：
           G1 Eden Space
           G1 Survivor Space
           G1 Old Gen

           元空间：
           Metaspace
           Compressed Class Space

           Code Cache
         *
         */
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean mxBean : memoryPoolMXBeans) {
            System.out.println(mxBean.getName());
        }
    }
}
